# -*- coding: utf-8 -*-
"""
产品模块视图函数
提供产品相关的API接口
"""

from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter

from .models import Product, ProductStatus
from .serializers import ProductSerializer, ProductSimpleSerializer


class ProductViewSet(viewsets.ModelViewSet):
    """
    产品视图集
    提供产品的增删改查功能
    """
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['sku', 'name', 'description', 'spc']
    ordering_fields = ['create_time', 'update_time', 'sku']
    ordering = ['-create_time']

    def get_queryset(self):
        """根据用户权限过滤产品"""
        queryset = super().get_queryset()
        # 处理is_active参数，将其映射到status字段
        is_active = self.request.query_params.get('is_active')
        if is_active is not None:
            is_active_bool = is_active.lower() in ('true', '1', 'yes')
            if is_active_bool:
                queryset = queryset.filter(status='active')
            else:
                queryset = queryset.exclude(status='active')
        # 可以根据用户角色或部门添加过滤逻辑
        return queryset

    @action(detail=True, methods=['get'])
    def simple_info(self, request, pk=None):
        """获取产品简要信息"""
        product = self.get_object()
        serializer = ProductSimpleSerializer(product)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def by_status(self, request):
        """根据状态获取产品列表"""
        status_param = request.query_params.get('status')
        if not status_param:
            return Response(
                {'error': '状态参数不能为空'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        products = Product.objects.filter(status=status_param)
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)